<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeGridListeners, VxeTableGridOptions } from '#/adapter/vxe-table'

import { h, ref } from 'vue'
import { useRouter } from 'vue-router'

import { Page, useVbenModal } from '@vben/common-ui'
import { AntCheckOutlined, AntCloseOutlined, AntDeleteOutlined, AntDownloadOutlined, AntPlusOutlined, AntTagOutlined, AntTagsOutlined } from '@vben/icons'
import { $t } from '@vben/locales'

import { useDebounceFn } from '@vueuse/core'
import { Button, message, Popconfirm, Spin } from 'ant-design-vue'

import CountTabs from '#/adapter/component/count-tabs.vue'
import fileManage from '#/adapter/component/FileManage/index.vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getAdminList, getGoodsTypeList } from '#/api/common'
import { doPurchaseAgainst, doPurchaseApproval, doPurchaseDelete, doSign, getPurchaseList } from '#/api/purchase'

import bachSubmint from './modules/bachSubmint/bachSubmintModel.vue'
import ExportContract from './modules/exportContract.vue'
import PurchaseForm from './modules/form.vue'
import PurchaseDetail from './modules/purchaseDetail.vue'
import PurchaseDetailBom from './modules/purchaseDetailBom.vue'
import TagContract from './modules/tagContract.vue'

interface RowType {
  [key: string]: any
}

const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'purchase_id',
  order: 'desc',
}
const keyword = ref({
  data_type: '',
  buyer_id: '',
})
const fetching = ref(false)
const router = useRouter()

// 获取选中的行数据
const selectedRows = ref<any[]>([])

// 审核按钮是否禁用 - 当选中行中有已审核的行时禁用
const isDisabledApproval = ref(true)
const DisabledApproval = () => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.Posted === 1)
}

// 反审按钮是否禁用 - 当选中行中有未审核的行时禁用
const isDisabledAgainst = ref(true)
const DisabledAgainst = () => {
  // 没有选中行 或者 有未审核的行，则禁用
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.Posted === 0)
}

// 财务标记按钮是否禁用 - 只有选中行且所有行都未标记时才启用
const isDisabledSuccess = ref(true)
const DisabledSuccess = () => {
  // 没有选中行 或者 有已标记的行，则禁用
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.is_cw_sign === 1)
}

// 财务反标记按钮是否禁用 - 只有选中行且所有行都已标记时才启用
const isDisabledError = ref(true)
const DisabledError = () => {
  // 没有选中行 或者 有未标记的行，则禁用
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.is_cw_sign === 0)
}

// 获取选中行的ID数组
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.purchase_id)
}

const getPostedOptions = () => {
  return [
    {
      color: 'success',
      label: '已审核',
      value: 1,
    },
    { color: 'error', label: '未审核', value: 0 },
  ]
}

const getHTsendOptions = () => {
  return [
    {
      color: 'success',
      label: '已发送',
      value: 1,
    },
    { color: 'error', label: '未发送', value: 0 },
  ]
}

const getTagOptions = () => {
  return [
    {
      color: 'success',
      label: '已标记',
      value: 1,
    },
    { color: 'error', label: '未标记', value: 0 },
  ]
}

const getUploadOptions = () => {
  return [
    {
      color: 'success',
      label: '已上传',
      value: 1,
    },
    { color: 'error', label: '未上传', value: 0 },
  ]
}

const fetchData = async () => {
  gridApi.reload()
}

/**
 * 获取远程选项
 */
async function fetchRemoteOptions({ keyword = '' }: Record<string, any>) {
  const { list } = await getAdminList({
    quick_search: keyword,
    is_caigou: true,
    group_id: 7,
    page: 1,
    limit: 100,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })

  return list.map((item) => ({
    label: item.realname,
    value: item.id,
  }))
}

/**
 * 获取远程选项
 */
async function fetchRemoteDataTypeOptions({ keyword = '' }: Record<string, any>) {
  const { list } = await getGoodsTypeList({
    is_select: true,
    page: 1,
    initKey: 'id',
    initValue: undefined,
    select: true,
    quick_search: keyword,
    limit: 100,
  })

  return list.map((item) => ({
    label: item.name,
    value: item.id,
  }))
}

const formOptions: VbenFormProps = {
  fieldMappingTime: [['date', ['start', 'end']]],
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'purchase_sn',
      label: '手工单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'caigou_id',
      label: '采购单号',
      operator: '=',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'supply_name',
      label: '供应商',
      operator: 'false',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'material_name',
      label: '物料名称',
      operator: 'false',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'template_no',
      label: '简码',
      operator: 'false',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'purchase_time',
      label: '采购日期',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchRemoteOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.buyer_id = value
          }, 300),
          params: {
            keyword: keyword.value.buyer_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value.buyer_id = ''
          },
        }
      },
      fieldName: 'buyer_id',
      label: '采购员',
      operator: 'IN',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Select',
      fieldName: 'Posted',
      label: '审核状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '已审核',
            value: 1,
          },
          {
            label: '未审核',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'Select',
      fieldName: 'is_send_contract',
      label: '合同是否发送',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '已发送',
            value: 1,
          },
          {
            label: '未发送',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'Select',
      fieldName: 'is_cw_sign',
      label: '标记状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '已标记',
            value: 1,
          },
          {
            label: '未标记',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'cw_sign_time',
      label: '财务标记/取消时间',
      operator: 'RANGE',
      valueToString: true,
    },
    {
      component: 'RangePicker',
      componentProps: {
        // showTime: true,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'audit_time',
      label: '审核时间',
      operator: 'RANGE',
      valueToString: true,
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchRemoteDataTypeOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.data_type = value
          }, 300),
          params: {
            keyword: keyword.value.data_type || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          maxTagCount: 'responsive',
          mode: 'multiple',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value.data_type = ''
          },
        }
      },
      fieldName: 'data_type',
      label: '人员类型',
      operator: 'IN',
      valueToString: false,
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '已上传',
            value: 1,
          },
          {
            label: '未上传',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
      fieldName: 'isUploadFile',
      label: '是否上传附件',
      operator: 'false',
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}
const searchValue: any = ref([])
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    trigger: 'row',
  },
  rowConfig: {
    // useKey: true,
    // keyField: 'material_id',
    // isCurrent: true,
    isHover: true,
  },
  rowStyle({ row, rowIndex }) {
    if (row.Posted === 0) {
      return {
        color: 'red',
      }
    }
  },
  columns: [
    { type: 'checkbox', width: 70, fixed: 'left' },
    { field: 'purchase_sn', width: 120, title: '手工单号', fixed: 'left' },
    { field: 'caigou_id', width: 120, title: '采购单号', fixed: 'left' },
    { field: 'supply_name', width: 120, title: '供应商' },
    { field: 'material_name', width: 120, title: '物料名称', visible: false },
    { field: 'template_no', width: 120, title: '简码', visible: false },
    { field: 'purchase_time', width: 120, title: '采购日期' },
    { field: 'admin.realname', width: 120, title: '采购员' },
    { field: 'total_confirm_num', width: 120, title: '采购总量' },
    { field: 'total_reviced_num', width: 120, title: '收料总量' },
    { field: 'total_refund_num', width: 120, title: '退料总量' },
    {
      field: 'Posted',
      width: 120,
      title: '审核状态',
      cellRender: { name: 'CellTag', options: getPostedOptions() },
    },
    {
      field: 'is_send_contract',
      width: 120,
      title: '合同是否发送',
      cellRender: { name: 'CellTag', options: getHTsendOptions() },
    },
    { field: 'contract_send_time', width: 120, title: '合同发出' },
    { field: 'contract_receive_time', width: 120, title: '合同签回' },
    { field: 'contract_remarks', width: 120, title: '合同备注' },
    {
      field: 'is_cw_sign',
      width: 120,
      title: '标记状态',
      cellRender: { name: 'CellTag', options: getTagOptions() },
    },
    {
      field: 'cw_sign_time',
      width: 120,
      title: '财务标记/取消时间',
      sortable: true,
    },
    { field: 'audit_time', width: 120, title: '审核时间', sortable: true },
    { field: 'createAdmin.realname', width: 120, title: '创建人' },
    { field: 'buyer_id', width: 120, title: '采购员' },
    { field: 'last_audit', width: 180, title: '最后审核' },
    { field: 'data_type', width: 120, title: '人员类型' },
    {
      field: 'isUploadFile',
      width: 120,
      title: '是否上传附件',
      cellRender: { name: 'CellTag', options: getUploadOptions() },
    },
    { field: 'last_save', width: 180, title: '最后修改' },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 300,
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 20,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const res2 = await getPurchaseList({
          search,
          requestType: 'nav',
        })

        search.push({ field: 'purchase.is_deleted', val: activeKey.value ? activeKey.value : undefined, operator: '=' })
        searchValue.value = search
        const res = await getPurchaseList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        })
        // 获取到tab

        tabsList.value = res2

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
    sort: true,
  },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'purchase_list',
  customConfig: {
    storage: true,
  },
}

function openModal(res) {
  PurchaseDetailModalApi.setData({
    info: res,
  }).open()
}

function openModalBom(res) {
  PurchaseDetailBomModalApi.setData({
    info: res,
  }).open()
}

function openModalForm(res) {
  PurchaseFormModalApi.setData({
    info: res,
  }).open()
}
function openExportContractForm() {
  ExportContractModalApi.setData({
    id_arr: getSelectionIds(),
  }).open()
}
function openTagContractForm() {
  TagContractModalApi.setData({
    info: selectedRows.value,
  }).open()
}

// 处理新建操作
const handleCreate = () => {
  PurchaseFormModalApi.setData({}).open()
}

// 新增确认删除函数
const handleDelete = () => {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting'),
    duration: 0,
    key: 'action_process_msg',
  })

  doPurchaseDelete({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess'),
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
  // 执行删除逻辑
  // console.log('删除选中的数据:', getSelectionIds());
}

// 处理审核操作
const handleApproval = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要审核的数据')
    return
  }
  const hideLoading = message.loading({
    content: '审核',
    duration: 0,
    key: 'action_process_msg',
  })

  doPurchaseApproval({ ids: getSelectionIds(), is_confirm_ware: 0 })
    .then(() => {
      message.success({
        content: '审核成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理反审操作
const handleAgainst = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要反审的数据')
    return
  }

  const hideLoading = message.loading({
    content: '反审',
    duration: 0,
    key: 'action_process_msg',
  })

  doPurchaseAgainst({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '反审成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理审核并推送操作
const handleApprovalAndPush = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要审核的数据')
    return
  }
  const hideLoading = message.loading({
    content: '审核',
    duration: 0,
    key: 'action_process_msg',
  })

  doPurchaseApproval({ ids: getSelectionIds(), is_new_button: 1 })
    .then(() => {
      message.success({
        content: '审核成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理财务标记操作
const handleFinanceMark = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要财务标记的数据')
    return
  }
  const hideLoading = message.loading({
    content: '财务标记',
    duration: 0,
    key: 'action_process_msg',
  })

  doSign({ ids: getSelectionIds(), type: 'success' })
    .then(() => {
      message.success({
        content: '财务标记成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理财务反标记操作
const handleFinanceUnmark = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要财务反标记的数据')
    return
  }
  const hideLoading = message.loading({
    content: '财务反标记',
    duration: 0,
    key: 'action_process_msg',
  })

  doSign({ ids: getSelectionIds(), type: 'error' })
    .then(() => {
      message.success({
        content: '财务反标记成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理附件管理操作
const handleFileManagement = () => {
  // 执行附件管理逻辑purchase_sn
  const data = gridApi.grid.getCheckboxRecords()
  const ids = data.map((item: any) => item.purchase_id)

  fileManageModalApi.setData({ data: ids, type: '1', search: searchValue.value }).open()
}

const [fileManageModal, fileManageModalApi] = useVbenModal({
  connectedComponent: fileManage,
})

const [PurchaseDetailModal, PurchaseDetailModalApi] = useVbenModal({
  connectedComponent: PurchaseDetail,
})

const [PurchaseDetailBomModal, PurchaseDetailBomModalApi] = useVbenModal({
  connectedComponent: PurchaseDetailBom,
})

const [PurchaseFormModal, PurchaseFormModalApi] = useVbenModal({
  connectedComponent: PurchaseForm,
})

const [ExportContractModal, ExportContractModalApi] = useVbenModal({
  connectedComponent: ExportContract,
})

const [TagContractModal, TagContractModalApi] = useVbenModal({
  connectedComponent: TagContract,
})

const gridEvents: VxeGridListeners<RowType> = {
  cellDblclick: ({ row }) => {
    openModalForm(row)
  },
  checkboxChange: (params) => {
    // console.log('checkboxChange', params);
    const checkData = gridApi.grid.getCheckboxRecords()
    // console.log('checkData', JSON.parse(JSON.stringify(checkData)));
    selectedRows.value = JSON.parse(JSON.stringify(checkData))
    ButtonDisabled()
  },
}

const ButtonDisabled = () => {
  isDisabledApproval.value = DisabledApproval()
  isDisabledAgainst.value = DisabledAgainst()
  isDisabledSuccess.value = DisabledSuccess()
  isDisabledError.value = new DisabledError()
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
})

// 批量提交物料采购单修改
const [bachSubmintModal, bachSubmintModalApi] = useVbenModal({
  connectedComponent: bachSubmint,
})
function batchSubmit() {
  bachSubmintModalApi.open()
}

// 新增tab
const activeKey = ref(2)
const tabsList: any = ref([])
// 切换tab
function resetQuery(e: any) {
  console.log(activeKey.value)
  gridApi.query()
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div style="display: flex; flex-direction: column">
          <div>
            <Button class="mr-2" type="primary" @click="handleCreate()">
              <AntPlusOutlined />
              新建
            </Button>

            <Popconfirm
              title="确认删除"
              :disabled="isDisabledApproval"
              :description="`确定要删除选中的 ${selectedRows.length} 条数据吗？此操作不可恢复。`"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleDelete"
              @cancel="() => {}"
            >
              <Button class="mr-2" type="primary" danger :disabled="isDisabledApproval">
                <AntDeleteOutlined />
                作废
              </Button>
            </Popconfirm>

            <Popconfirm title="确认审核" :disabled="isDisabledApproval" :description="`确定要审核选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleApproval" @cancel="() => {}">
              <Button type="ghost" class="mr-2" :class="[isDisabledApproval ? 'ant-btn-disabled' : 'bg-[#24b916] text-white hover:opacity-75']" :disabled="isDisabledApproval">
                <AntCheckOutlined />
                审核
              </Button>
            </Popconfirm>
            <Popconfirm title="确认反审" :disabled="isDisabledAgainst" :description="`确定要反审选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleAgainst" @cancel="() => {}">
              <Button type="ghost" class="mr-2" :class="[isDisabledAgainst ? 'ant-btn-disabled' : 'bg-[#f56c6c] text-white hover:opacity-75']" :disabled="isDisabledAgainst">
                <AntCloseOutlined />
                反审
              </Button>
            </Popconfirm>

            <Button type="ghost" class="mr-2 bg-[#67c23a] text-white hover:opacity-75" @click="openExportContractForm()">
              <AntDownloadOutlined />
              导出合同
            </Button>
            <Button type="ghost" class="mr-2 bg-[#e6a23c] text-white hover:opacity-75" @click="openTagContractForm()">
              <AntTagsOutlined />
              标记合同
            </Button>
            <Button class="mr-2" type="primary" @click="handleApprovalAndPush()" :disabled="isDisabledApproval">
              <AntCheckOutlined />
              审核并推送（新）
            </Button>

            <Popconfirm
              title="确认财务标记"
              :disabled="isDisabledSuccess"
              :description="`确定要财务标记选中的 ${selectedRows.length} 条数据吗？`"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleFinanceMark"
              @cancel="() => {}"
            >
              <Button type="ghost" class="mr-2" :class="[isDisabledApproval ? 'ant-btn-disabled' : 'bg-[#24b916] text-white hover:opacity-75']" :disabled="isDisabledSuccess">
                <AntTagsOutlined />
                财务标记
              </Button>
            </Popconfirm>
            <Popconfirm
              title="确认财务标记"
              :disabled="isDisabledError"
              :description="`确定要财务标记选中的 ${selectedRows.length} 条数据吗？`"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleFinanceUnmark"
              @cancel="() => {}"
            >
              <Button type="ghost" class="mr-2" :class="[isDisabledError ? 'ant-btn-disabled' : 'bg-[#f56c6c] text-white hover:opacity-75']" :disabled="isDisabledError">
                <AntTagOutlined />
                财务反标记
              </Button>
            </Popconfirm>
            <Button type="ghost" class="mr-2 bg-[#67c23a] text-white hover:opacity-75" @click="handleFileManagement()">
              <AntDownloadOutlined />
              附件管理与导出
            </Button>
            <Button class="mr-2" type="primary" @click="batchSubmit()">采购单修改</Button>
          </div>
          <div style="margin-top: 10px; width: 1000px">
            <CountTabs v-model:active-key="activeKey" :list="tabsList" @click-tab="resetQuery" :disabled="false" />
          </div>
        </div>
      </template>
      <template #operation="{ row }">
        <Button class="mr-2" type="primary" size="small" @click.stop="openModalForm(row)">编辑</Button>
        <Button class="mr-2" size="small" @click.stop="openModalBom(row)">查看报单</Button>
        <Button class="mr-2" size="small" @click.stop="openModal(row)">查看报单（工作台）</Button>
      </template>
    </Grid>
    <PurchaseDetailModal @fetch-data="fetchData" />
    <PurchaseDetailBomModal @fetch-data="fetchData" />
    <PurchaseFormModal @fetch-data="fetchData" />
    <ExportContractModal @fetch-data="fetchData" />
    <TagContractModal @fetch-data="fetchData" />
    <fileManageModal @close="fetchData" />
    <bachSubmintModal />
  </Page>
</template>
